package fans_messages

import (
	"encoding/json"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/chat"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/pkg/common/helper/blackWorlds"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"
)

const (
	//  0-普通文本消息 1-加入提示 2-撤回 3-删除 4-被踢出 5-被禁言 6-解禁 7-图文消息
	TextType MsgSendType = iota
	JoinType
	ReCallType
	DeleteType
	KickOutType
	BanType
	UnbanType
	ImageTextType
)

type (
	SayContent  string
	MsgSendType int
	// SayMessage 发言
	SayMessage struct {
		IncomingMessage
		Content     SayContent `json:"content"`
		ImageUrl    string     `json:"image_url"`
		ImageWidth  int        `json:"image_width"`
		ImageHeight int        `json:"image_height"`
	}
	SayRepMessage struct {
		messages2.ReplyMessage
		Resp SayRespMessage `json:"resp"`
	}

	SayRespMessage struct {
		Seq         int64       `json:"seq"`          // 消息ID （Seq + 群ID  删除指定消息）
		Uid         int         `json:"uid"`          // 发送用户ID
		GroupId     string      `json:"group_id"`     // 群ID
		NickName    string      `json:"nick_name"`    // 昵称
		Avatar      string      `json:"avatar"`       // 头像
		Content     SayContent  `json:"content"`      // 发送的内容
		SendTime    int64       `json:"send_time"`    // 发送时间
		Type        MsgSendType `json:"type"`         // 消息类型 0-普通文本消息 1-加入提示 2-撤回 3-删除 4-被踢出 5-被禁言 6-解禁 7-图文消息
		Role        int         `json:"role"`         // 角色 0-群员 1-管理 2-群主 3-机器人
		ImageUrl    string      `json:"image_url"`    // 图文消息的图片链接
		ImageWidth  int         `json:"image_width"`  // 图文消息的图片宽度
		ImageHeight int         `json:"image_height"` // 图文消息的图片高度
	}
)

func SayMessageHandler(rawBytes []byte, pbReq *pb.CallbackReq, user *chat.ClientUser) *pb.CallbackResp {
	req := SayMessage{}
	err := json.Unmarshal(rawBytes, &req)
	if err != nil {
		return utils.FailCodeResp(imsdk.TIM_ERROR_CODE_REJECT, "消息识别错误")
	}

	if len(req.Content) <= 0 && len(req.ImageUrl) <= 0 {
		return utils.FailCodeResp(imsdk.TIM_FANSG_REJECT_FAILTIPS, "发送失败，请重新上传")
	}

	content, err := req.Content.replaceWord()
	if err != nil {
		return utils.FailCodeResp(imsdk.TIM_ERROR_CODE_REJECT, err.Error())
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id":       user.UserId,
		"fans_group_id": pbReq.GroupId,
	})
	if err != nil {
		global.Log.Error(err)
		return utils.FailCodeResp(imsdk.TIM_FANSG_REJECT_FAILTIPS, "您未加群")
	}
	resp := SayRepMessage{
		ReplyMessage: messages2.ReplyMessage{Type: messages2.SayReplyMessageType},
		Resp: SayRespMessage{
			//Seq:      pbReq.MsgSeq, // before时不会有seq
			Uid:      user.UserId,
			GroupId:  pbReq.GroupId,
			NickName: user.ClientName,
			Avatar:   user.Avatar,
			Content:  SayContent(content),
			SendTime: time.Now().Unix(), // before发言时，没有时间
			Type:     TextType,
			Role:     gcUser.Role,
		},
	}

	if len(req.ImageUrl) > 0 {
		resp.Resp.Type = ImageTextType
		resp.Resp.ImageUrl = req.ImageUrl
		resp.Resp.ImageWidth = req.ImageWidth
		resp.Resp.ImageHeight = req.ImageHeight
	}
	return utils.CallbackOkResp(resp)
}

func (m SayContent) replaceWord() (string, error) {
	// msg.MsgContent.Text 需要加解密
	content := m.Decode()
	replace := blackWorlds.BlackWorInstance.ReplaceWithAsterisk(content)
	return cache.AesEncrypt(replace)

}

func (m SayContent) Decode() string {
	say := string(m)
	var content string
	var err error
	if len(say) > 0 {
		content, err = cache.AesDescrypt(say)
		if err != nil {
			//encrypt, _ := cache2.AesEncrypt("测试消息")
			//global.Log.Debug("decode test: ", encrypt)
			global.Log.Error("decode error: ", err)
			return say
		}
	}
	return content
}
